import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import { formatMessage } from 'umi-plugin-react/locale';
import SelectForm from '@/components/SelectForm';
import RightDraw from '@/components/RightDraw';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import { columnsDriver, columns1, supplierColumns } from '@/pages/Common/common';
import { vitifyCheck, queryPerson, queryDict, formateDateToMin, formatPrice } from '@/utils/common';
import ArchivesDetail from './ArchivesDetail';
import ArchivesOneTeamDetail from './ArchivesOneTeamDetail';
import ArchivesDetailHK from './ArchivesDetailHK';
import ArchivesDetailEmpty from "./ArchivesDetailEmpty";
import EmptyArchivesForm from './EmptyArchivesForm';
import {
    allDispatchType,
    selectArchivesList,
    saveAllValues,
    renderTableAdSelect,
    renderTableAdSearch,
    codes,
    archivesStatusList,
    allUrl,
    routeUrl,
    selectArchivesDetailAndInfo,
    checkConfirm,
} from './utils';
import { is } from '@babel/types';
import ButtonGroup from 'antd/lib/button/button-group';
import { Prompt } from 'dva/router';
import prompt from '@/components/Prompt';

const { confirm } = Modal;
const dateFormat = 'YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { MonthPicker } = DatePicker;

@ManageList
@connect(({ Archives, loading, component }) => ({
    trainInfoList: Archives.trainInfoList,
    pressureInfoList: Archives.pressureInfoList,
    archivesList: Archives.archivesList,
    oilInfoList: Archives.oilInfoList,
    feeData: Archives.feeData,
    archivesDetail: Archives.archivesDetail,
    emptyDetails: Archives.emptyDetails,
    formValues: Archives.formValues,
    dictObject: component.dictObject,
    searchValue: component.searchValue,
    loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class ArchivesList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            expandForm: false,
            archivesInfo: {},
            visible: false,
            detailId: '',
            recordStatus: '',
            selectedRows: [],
            company: [],
            cars: [],
            drivers: [],
            companyType: '',
            isHK: false,
            visibleEmpty: false,
            businessType: ''
        };
        this.className = 'archives-table';
    }

    componentWillMount() {
        // 查询字典项
        const allDict = [allDictList.businessType];
        queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const { form, formValues } = this.props;
        const props = { props: this.props };
        form.resetFields();
        saveAllValues({ payload: { formValues: {} }, ...props });
        selectArchivesList({ props: this.props ,payload:{pageType:'ECD'} });
    }

    /**
     * form 查找条件 重置
     */
    handleFormReset = () => {
        const { form, formValues } = this.props;
        const props = { props: this.props };
        this.setState({
            company: [],
            cars: [],
            drivers: [],
        });
        form.resetFields();
        saveAllValues({ payload: { formValues: {} }, ...props });
        selectArchivesList({ ...props,payload:{pageType:'ECD'}  });
    };

    /**
     * form 查找条件 查询
     */
    handleSearch = formValues => {
        // if (!formValues) return;
        const { company, cars, drivers } = this.state;
        const { mdsCompanyId, settlementDate, transportStartTime, transportEndTime, vehicleId, ...param } = formValues;
        if (company.length > 0) {
            const mdsCompanyId = company.map(v => {
                return v.customerCode;
            });
            param.mdsCompanyId = mdsCompanyId.join(',');
        }
        if (cars.length > 0) {
            const vehicleId = cars.map(v => {
                return v.id;
            });
            param.vehicleId = vehicleId.join(',');
        } else {
            param.vehicleId = '';
        }
        if (drivers.length > 0) {
            param.driverId = drivers[0].id;
        } else {
            param.driverId = ''
        }
        
        if (transportStartTime&&transportStartTime.length>0) {
            param.transportStartTimeStart = moment(transportStartTime[0]).format(dateFormat);
            param.transportStartTimeEnd = moment(transportStartTime[1]).format(dateFormat);
        }else{
            param.transportStartTimeStart=''
            param.transportStartTimeEnd=''
        }
        if (transportEndTime&&transportEndTime.length>0) {
            param.transportEndTimeStart = moment(transportEndTime[0]).format(dateFormat);
            param.transportEndTimeEnd = moment(transportEndTime[1]).format(dateFormat);
        }else{
            param.transportEndTimeStart=''
            param.transportEndTimeEnd=''
        }
        if (settlementDate)
            param.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';
        param.pageType='ECD'
        const params = { props: this.props, payload: param };
        saveAllValues({ payload: { formValues: param }, props: this.props });
        selectArchivesList(params);
    };

    /**
     * table 表格 分页操作
     */
    handleStandardTableChange = param => {
        const { formValues } = this.props;
        selectArchivesList({ payload: { ...formValues, ...param,pageType:'ECD' }, props: this.props });
    };

    //详情
    showDetail = (e, record) => {
        // console.log('12334')
        e.stopPropagation();
        const { id, status, businessType } = record;
        const isHK = businessType == 'LOCAL' || businessType == 'HK' || businessType == 'HK_NONSTOP' || businessType == 'EMPTY';
        this.handleStateChange([{ isHK }, { businessType }, { detailId: id }, { recordStatus: status }, { visible: true }]);
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    //新建国内车
    handleAdd = () => {
        router.push(routeUrl.add);
    };
    //新建一车队
    motorcadeEmpty = (YCD) => {
        router.push(routeUrl.addOneTeam)
    }
    
    //编辑
    handleEdit = (isHK) => {
        const { detailId, businessType } = this.state;
        this.handleStateChange([{ visible: false }]);
        if (businessType == 'EMPTY') {
            router.push(`${routeUrl.editEmpty}/${detailId}`)
        } else if (isHK) {
            router.push(`${routeUrl.editHK}/${detailId}`)
        } else if (businessType == 'ONE_TEAM') {
            router.push(`${routeUrl.editOneTeam}/${detailId}`)
        } else {
            router.push(`${routeUrl.edit}/${detailId}`)

        }
    };

    columns = [
        {
            title: '档案编号',
            dataIndex: 'archivesNo',
            render: (text, record) => (
                <AdButton
                    mode="a"
                    onClick={e => this.showDetail(e, record)}
                    text={text}
                    code={codes.showDetail}
                />
            ),
            fixed: this.props.isMobile ? false : true,
        },
        {
            title: '业务类型',
            dataIndex: 'businessType',
            width: 100,
            render: text =>
                renderTableAdSelect({
                    props: this.props,
                    value: text || 'INLAND',
                    key: allDictList.businessType
                })
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            render: text =>
                renderTableAdSelect({ props: this.props, value: text, data: archivesStatusList }),
        },
        {
            title: '车牌号',
            dataIndex: 'cartPlate',
        },
        // {
        //   title: '车挂',
        //   dataIndex: 'cartHangingName',
        // },
        {
            title: '司机',
            dataIndex: 'driverName',
            render: text => <span title={text}>{text}</span>
        },
        {
            title: '所属公司',
            dataIndex: 'ownCompanyName',
            render: text => <span title={text}>{text}</span>,
            width: 250,
        },
        {
            title: 'ETC发车金额',
            dataIndex: 'etcStartAmount',
            width: 100,
            render: text => <span>{formatPrice(text)}</span>,
        },
        {
            title: 'ETC收车金额',
            dataIndex: 'etcEndAmount',
            width: 100,
            render: text => <span>{formatPrice(text)}</span>,
        },
        {
            title: '车次号',
            dataIndex: 'trains',
        },
        {
            title: '车次数',
            dataIndex: 'trainsCount',
            width: 100,
        },
        {
            title: '发车时间',
            dataIndex: 'transportStartTime',
        },
        {
            title: '收车时间',
            dataIndex: 'transportEndTime',
        },
        {
            title: '发车里程(KM)',
            dataIndex: 'startMileage',
            width: 100,
        },
        {
            title: '收车里程(KM)',
            dataIndex: 'collectMileage',
            width: 100,
        },
        {
            title: '行驶里程(KM)',
            dataIndex: 'travelMileage',
            width: 100,
        },
        {
            title: '耗油量(L)',
            dataIndex: 'consumptionOil',
            width: 100,
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            width: 100,
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
        {
            title: '更新人',
            dataIndex: 'updateBy',
            width: 100,
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
    ];

    //删除,作废
    removeArchives = type => {
        const { dispatch, formValues } = this.props;
        const { detailId } = this.state;
        confirm({
            title: `确定要${type == 'del' ? '删除' : '作废'}这条数据吗？`,
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: type == 'del' ? allDispatchType.remove : allDispatchType.cancel,
                    payload: { id: detailId },
                    callback: data => {
                        if (!data) return;
                        this.setState({ visible: false }); 
                        selectArchivesList({ props: this.props, payload: {...formValues,pageType:'ECD'} });
                    },
                });
            },
        });
    };

    // 确认、试算、提交
    operateArchives = (type, single) => {
        const { dispatch, formValues, feeData } = this.props;
        const { selectedRows, detailId, isHK, businessType } = this.state;
        const id = detailId;
        const ids = selectedRows.map(v => {
            return v.id;
        });
        //status === 'CONFIRM'
        let isReturn=false
        // selectedRows.forEach(v=>{
        //     if(v.status ==='CONFIRM'){
        //         prompt({content:'请选择已确认的档案',type:'warn'})
        //         isReturn=true
        //     }
        // })
        if(isReturn) return
        let url = allDispatchType.detail;
        let payloads = { id, isHK };
        if (businessType === 'EMPTY') {
            url = allDispatchType.selectEmptyDetails;
            payloads = { id };
        }

        const unit = {
            callDispatch: () => {
                selectArchivesDetailAndInfo({
                    type: url,
                    payload: payloads,
                    props: this.props,
                    callback: data => {
                        if (!data) return;
                        this.setState({
                            recordStatus: data.status,
                        });
                    },
                });
                selectArchivesList({ props: this.props, payload: {...formValues,pageType:'ECD' }});
            },
            callCommit: (tips = "") => {
                confirm({
                    title: `${tips}提交后数据将不能进行修改，是否进行提交？`,
                    content: ' ',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        dispatch({
                            type: allDispatchType.commit,
                            payload: { ids: single ? [id] : ids },
                            callback: data => {
                                if (!data) return;
                                unit.callDispatch();
                            },
                        });
                    },
                });
            },
        };

        //批量提交时：后台校验
        if (type == 'commit' && ((feeData && feeData[id]) || !single)) {
            unit.callCommit();
            return;
        }
        checkConfirm({
            props: this.props,
            id,
            type,
            isHK,
            callback: () => {
                if (type == 'confirm') {
                    //确认
                    dispatch({
                        type: allDispatchType.confirm,
                        payload: { id },
                        callback: data => {
                            unit.callDispatch(data);
                        },
                    });
                } else {
                    //试算和提交
                    if (type == 'commit') {
                        const tips = '费用已计算，';
                        unit.callCommit(tips);
                    }else{
                        dispatch({
                            type: allDispatchType.trial,
                            payload: { id, type },
                            callback: data => {
                                //试算完数据回显处理：未做
                                this.setState({});
                            },
                        });
                    }
                }
            },
        });
    };
    getValue = (values, type) => {
        console.log('getValue??',values, type)
        this.setState({
            [type]: values,
        });
    };
    //转为本地<-->重新拉取
    pullOrLocal = (type) => {
        const { dispatch, formValues } = this.props;
        const { detailId, isHK } = this.state;
        dispatch({
            type: allDispatchType[type],
            payload: { id: detailId },
            callback: data => {
                // if (!data) return;
                selectArchivesList({ props: this.props, payload: formValues });
                selectArchivesDetailAndInfo({
                    type: allDispatchType.detail,
                    payload: { id: detailId, isHK },
                    props: this.props,
                    callback: data => {
                        this.setState({
                            recordStatus: data.status,
                            businessType: data.businessType
                        }, () => {
                            console.log('businessType', this.state.businessType)
                        });
                    },
                });
            },
        });
    }

    modalEmpty = (type) => {
        if (type == 'add') {
            this.setState({
                detailId: '',
            })
        }
        this.setState((pre) => ({
            visibleEmpty: !pre.visibleEmpty
        }))
    }
    abledStatus=(type)=>{
        const {selectedRows,formValues}=this.state
        const {dispatch}=this.props
        let isReturn=false
        selectedRows.forEach(v=>{
            if(v.status!=='SUBMITTED'){
                prompt({content:'请选择已提交档案',type:'warn'})
                isReturn=true
            }
        })
        if(isReturn) return
        const params={
            type,
            ids:selectedRows.map(v=>v.id)
        }
        console.log('type',)
        dispatch({
            type:'Archives/abledStatus',
            payload:params,
            callback:data=>{
                selectArchivesList({ props: this.props, payload: formValues });
            }

        })
    }
    render() {
        const { archivesList, loading, form, isMobile, dictObject, emptyDetails, archivesDetail } = this.props;
        const { businessType, expandForm, detailId, visible, recordStatus, selectedRows, isHK, visibleEmpty } = this.state;
        let detail = {};
        if (businessType === 'EMPTY') {
            detail = emptyDetails[detailId] || {};
        } else {
            detail = archivesDetail[detailId] || {};
        }
        const commonParams = {
            getFieldDecorator: form.getFieldDecorator,
        };
        const firstFormItem = (
            <AntdFormItem label="档案编号" code="archivesNo" {...commonParams}>
                <Input />
            </AntdFormItem>
        );
        const secondFormItem = (
            <AntdFormItem label="车牌号" code="vehicleId" {...commonParams}>
                <SearchSelect
                    dataUrl="tms/tms-vehicle/selectListByArchives"
                    url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                    selectedData={this.state.cars} // 选中值
                    multiple={false} // 是否多选
                    showValue="cartPlateOneNo"
                    searchName="cartPlate"
                    columns={columns1} // 表格展示列
                    onChange={values => this.getValue(values, 'cars')} // 获取选中值
                    scrollX={480}
                    id="ArchivesList_1"
                    allowClear={true}
                    payload={{ categoryList: ['HEADSTOCK', 'CARLOAD'] }} //筛选为整车和车头的
                />
            </AntdFormItem>
        );
        // secondForm 参数
        const otherFormItem = [
            [
                <AntdFormItem label="司机" code="driverId" {...commonParams}>
                    <SearchSelect
                        multiple={false} // 是否多选
                        dataUrl="tms/tms-driver-archives/selectDriverList"
                        url="tms/tms-driver-archives/selectDriverView_s"
                        selectedData={this.state.drivers} // 选中值
                        columns={columnsDriver} // 表格展示列
                        onChange={values => this.getValue(values, 'drivers')} // 获取选中值
                        id="ArchivesList_2"
                        scrollX={500}
                        allowClear={true}
                    />
                </AntdFormItem>,
            ],
            [
                // 所属公司
                <AntdFormItem label="所属公司" code="mdsCompanyId" {...commonParams}>
                    <SearchSelect
                        dataUrl={allUrl.companyList}
                        selectedData={this.state.company} // 选中值
                        multiple={false} // 是否多选
                        showValue="customerName"
                        searchName="customerName"
                        allowClear={true}
                        columns={supplierColumns} // 表格展示列
                        onChange={values => this.getValue(values, 'company')} // 获取选中值
                        scrollX={400}
                        id="ArchivesList_company_3"
                    />
                </AntdFormItem>,
                <AntdFormItem label="车次号" code="trainNo" {...commonParams}>
                    <Input />
                </AntdFormItem>,
                <AntdFormItem label="状态" code="status" {...commonParams}>
                    <AdSelect isExist={true} data={archivesStatusList} mode="multiple" />
                </AntdFormItem>,
            ],
            [

                <AntdFormItem label="发车时间" code="transportStartTime" {...commonParams}>
                    <AntdDatePicker mode="range" />
                </AntdFormItem>,
                <AntdFormItem label="收车时间" code="transportEndTime" {...commonParams}>
                    <AntdDatePicker mode="range" />
                </AntdFormItem>,
                <AntdFormItem label="结算周期" code="settlementDate" {...commonParams}>
                    <MonthPicker style={{ width: "100%" }} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem label="业务类型" code="businessType" {...commonParams}>
                    <AdSelect payload={{ code: allDictList.businessType }} />
                </AntdFormItem>,
                'operatorButtons'
            ]
        ];
        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            form,
            className: this.className,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
            toggleForm: expandForm => {
                this.handleStateChange([{ expandForm }]);
            },
            code: codes.select,
        };
        const _disabled = selectedRows.length > 0 && selectedRows.some(v => v.status !== 'SUBMITTED')
        const tableButtonsParams = {
            handleAdd: this.handleAdd,
            code: codes.add,
            addName: '+ 二车队行车档案',

            // rightButtons: (
            //     <AdButton
            //         style={{ marginLeft: 8 }}
            //         onClick={() => this.modalEmpty('add')}
            //         text="+ 中港车放空档案"
            //         code={codes.addHK}
            //     />
            // ),
            // rightButtonsFist: (
            //     <AdButton
            //         style={{ marginLeft: 8 }}
            //         onClick={() => this.motorcadeEmpty('YCD')}
            //         text="+ 一车队行车档案"
            //         code={codes.addYCD}
            //     />

            // ),
            buttons: (
                <Button.Group>
                    <AdButton
                    style={{ marginLeft: 8 }}
                    disabled={!_disabled}
                    onClick={() => this.operateArchives('commit', 0, isHK)}
                    text="批量提交"
                    code={codes.commit}
                />
                <AdButton
                    disabled={!selectedRows.length > 0}
                    onClick={() => this.abledStatus('back')}
                    text="回退"
                    code={codes.commit}
                />
                </Button.Group>
            ),
        };

        // 详情 参数
        const disabled = recordStatus == 'SUBMITTED' ? true : false;

        const rightDrawParams = {
            isMobile,
            visible,
            title: '行车档案详情',
            code: codes.showDetail,
            closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
            buttons: (
                <>
                   
                    {
                        isHK
                            ?
                            <>
                                {/* 草稿状态的中港车的行车档案可以进行作废 */}
                                {
                                    detail.status === 'UNSEALED' && <AdButton
                                        onClick={() => this.removeArchives('cancle')}
                                        disabled={disabled}
                                        text="作废"
                                        type="danger"
                                        ghost
                                        code={codes.cancle}
                                        style={{ marginRight: 8 }}
                                    />
                                }
                                {
                                    businessType !== "EMPTY" && <AdButton
                                        onClick={() => this.pullOrLocal('pull')}
                                        disabled={disabled}
                                        text="重新拉取"
                                        code={codes.pull}
                                    />
                                }
                                {
                                    businessType == "HK_NONSTOP" && <AdButton
                                        onClick={() => this.pullOrLocal('toLocal')}
                                        disabled={disabled}
                                        style={{ marginLeft: 8 }}
                                        text="转为本地LOCAL"
                                        code={codes.toLocal}
                                    />
                                }

                            </>
                            :
                            <AdButton
                                onClick={() => this.removeArchives('del')}
                                disabled={disabled}
                                text="删除"
                                type="danger"
                                ghost
                                code={codes.remove}
                            />
                    }

                    <Button.Group style={{ marginLeft: 8 }}>
                        {detail.status == 'CONFIRM' && (
                            <>
                                <AdButton
                                    text="费用试算"
                                    code={codes.trial}
                                    onClick={() => this.operateArchives('trial', 0, isHK)}
                                    disabled={disabled}
                                />
                                <AdButton
                                    text="提交"
                                    code={codes.commit}
                                    onClick={() => this.operateArchives('commit', 1, isHK)}
                                    disabled={disabled}
                                />
                            </>
                        )}
                        {detail.status == 'UNSEALED' && (
                            <AdButton
                                onClick={() => this.operateArchives('confirm', 0, isHK)}
                                disabled={disabled}
                                text="审核确认"
                                code={codes.confirm}
                            />
                        )}

                        <AdButton
                            type="primary"
                            onClick={() => this.handleEdit(isHK)}
                            disabled={disabled}
                            text="编辑"
                            code={codes.edit}
                        />
                    </Button.Group>
                </>
            ),
        };


        return (
            <Fragment>
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    // disabledRowSelected={true}
                    selectedRows={selectedRows}
                    onSelectRow={selectedRows => {
                        this.handleStateChange([{ selectedRows }]);
                    }}
                    loading={loading}
                    data={archivesList}
                    columns={this.columns}
                    onPaginationChange={this.handleStandardTableChange}
                    expandForm={expandForm}
                    className={this.className}
                    code={codes.page}
                    disabledSelectedRows={{ code: ['status'], value: ['CONFIRM'] }}
                    getCheckboxProps={record => {
                        const status = record.status;
                        const checked = status === 'CONFIRM' || status === 'SUBMITTED';
                        return !checked;
                    }}
                />
                <RightDraw {...rightDrawParams}>
                    {
                        isHK ?
                            (
                                businessType == 'EMPTY' ?
                                    <ArchivesDetailEmpty businessType={businessType} detailId={detailId} visible={visible} />
                                    :
                                    <ArchivesDetailHK businessType={businessType} isHK={isHK} detailId={detailId} visible={visible} />
                            ) :
                            (businessType == 'ONE_TEAM' ?
                                <ArchivesOneTeamDetail isHK={isHK} detailId={detailId} visible={visible} />

                                :
                                <ArchivesDetail isHK={isHK} detailId={detailId} visible={visible} />
                            )
                    }

                </RightDraw>
                {
                    visibleEmpty && <EmptyArchivesForm
                        visible={visibleEmpty}
                        modalEmpty={this.modalEmpty}
                        detailId={detailId}
                    />
                }
            </Fragment>
        );
    }
}
